public with sharing class Callidus_ReassignApprovalRequest 
{
    private String currentPageURL;
    private ID salesContractId;
    private ID processInstanceWorkItemId;
    private Sales_Contract__c[] scList;
    
    private DataAccessControlUtil dacu = null;
    private Map<String, Schema.SObjectField> scSObjectFieldMap = new Map<String, Schema.SObjectField>(); 
    private String constructSoql;
    public String back2PlanURL {
        get 
        {
            if(Apexpages.currentPage().getParameters().get('rpg') != null && Apexpages.currentPage().getParameters().get('rpg') == '1')
                return '/apex/Sales_Contract_Custom_Page_For_RM?id='+salesContractId;
            else
                return '/home/home.jsp';///apex/Sales_Contract_CustomPage?id='+salesContractId;
        }
    }
    
    public Sales_Contract__c sContract {get; set;}
    public Plan_Document_Inquiry__c pdi {get; set;}
    public ProcessInstanceWorkitem piwi {get; set;}
    public String comments {get; set;}
    
    public Callidus_ReassignApprovalrequest()
    {
        pdi = new Plan_Document_Inquiry__c();
        piwi = new ProcessInstanceWorkitem();
        
        PageReference pg = Apexpages.currentPage();
        currentPageURL = pg.getUrl();
        
        salesContractId = pg.getParameters().get('id');
        processInstanceWorkItemId = pg.getParameters().get('pid');
        
        dacu = new DataAccessControlUtil();
        SObject scObj = new Sales_Contract__c();

        scSObjectFieldMap = dacu.getFieldMap(scObj);
        
        String[] expectedFields = new String[]{'id', 'name', 'createdbyId','ownerid'}; 
        
        Set<String> allowedFields = dacu.getAccessibleFields(scObj, scSObjectFieldMap, expectedFields);
        
        if(!allowedFields.isEmpty())
        {
            constructSoql = 'Select ';
            for(String roField: allowedFields)
            {
                constructSoql += roField+', ';
            }
            constructSoql = constructSoql.substring(0, constructSoql.length() - 2);
            constructSoql += '  from Sales_Contract__c where id = :salesContractId ';
            
            scList = Database.query(constructSoql);
            sContract = scList[0];
        }
        
        ProcessInstance[] prInst = [Select Id from ProcessInstance where TargetObjectId=:salesContractId and Status='Pending'];
        if(prInst.size()>0)     
        {
            ProcessInstanceWorkitem[] prInstWItem = [select Id, ProcessInstanceId, OriginalActorId, ActorId from ProcessInstanceWorkitem where ProcessInstanceId = :prInst[0].Id]; 
            if(prInstWItem.size() > 0)
            {
                piwi = prInstWItem[0]; 
            } 
        }       
    }
    
    public PageReference reassign()
    {
        piwi.ActorId = sContract.ownerId;//pdi.User__c;
        update piwi;

        dacu = new DataAccessControlUtil();
        SObject scObj = new Sales_Contract__c();

        scSObjectFieldMap = dacu.getFieldMap(scObj);
        
        String[] expectedFields = new String[]{'id', 'ownerid'}; 
        
        Set<String> allowedFields = dacu.getAccessibleFields(scObj, scSObjectFieldMap, expectedFields);
        
        if(!allowedFields.isEmpty())
        {
            constructSoql = 'Select ';
            for(String roField: allowedFields)
            {
                constructSoql += roField+', ';
            }
            constructSoql = constructSoql.substring(0, constructSoql.length() - 2);
            constructSoql += '  from Sales_Contract__c where id = :salesContractId ';
            
            scList = Database.query(constructSoql);
        }
        

		if(scList.size() > 0 && sContract.ownerid != scList[0].ownerId)
		{
	        Sales_Contract__Share scShare  = new Sales_Contract__Share();
	        scShare.ParentId = salesContractId;
	        scShare.UserOrGroupId = sContract.ownerId;//pdi.User__c;
	        scShare.AccessLevel = 'edit';
	         
	        CallidusPlanControl__c cpc = CallidusPlanControl__c.getInstance(UserInfo.getUserId());
	        if(cpc != null)
	        {
	            if(cpc.Can_View__c == true && cpc.Can_Reject__c == true && cpc.Can_Accept__c == true)
	            {
	            
	                ESAPI.accessController().setSharingMode(SFDCAccessController.SharingMode.WITHOUT);
	                try
	                {
	                	Sobject[] sObjList = [select id from Sales_Contract__Share where ParentId = :salesContractId and AccessLevel != 'All'];
	                	SFDCAccessControlResults.DeleteResults results = ESAPI.accessController().deleteAsUser(sObjList); 
	                	
	                    SObject sobj = ESAPI.accessController().insertAsUser(scShare, new List<String>{'ParentId', 'UserOrGroupId', 'AccessLevel'});
	                }
	                catch(SFDCAccessControlException e)
	                {
	                	ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
	                }
	            }
	        }
		}
        PageReference pg = new PageReference(back2PlanURL);
        
        return pg;        
    }

}